package servlet;


import util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/userList.do")
//@WebServlet("/SearchUserServlet.do")
public class UserListServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Map<String, Object>> userList = new ArrayList<>();
        JDBCUtil jdbcUtil = new JDBCUtil();
        try {
            String sql = "SELECT * FROM 02_38_yangyang"; // 假设数据库表名为 users
            ResultSet resultSet = jdbcUtil.query(sql);

            while (resultSet.next()) {
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                String gender = resultSet.getString("gender");
                String profession = resultSet.getString("profession");
                String favor = resultSet.getString("favor");
                String description = resultSet.getString("description");

                // Check for null values before adding to the map
                if (username != null && password != null && gender != null && profession != null && favor != null && description != null) {
                    Map<String, Object> user = Map.of(
                            "username", username,
                            "gender", gender,
                            "profession", profession,
                            "favor", favor,
                            "description", description
                    );

                    userList.add(user);
                }
            }

            // 将 userList 存储为请求属性
            request.setAttribute("userList", userList);

            request.getRequestDispatcher("/manageruser.jsp").forward(request, response);

        } catch (SQLException e) {
            e.printStackTrace();
            // 处理数据库异常
            // 可以跳转到错误页面或返回错误信息
        } finally {
            jdbcUtil.closeConnection();
        }
    }
}
